package com.bistu.openlab.uofspreadsheet.xmlparse;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.bistu.openlab.uofspreadsheet.model.ExcelContent;
import com.bistu.openlab.uofspreadsheet.model.ExcelSheet;
import com.bistu.openlab.uofspreadsheet.model.ExcelSheetAtt;
import com.bistu.openlab.uofspreadsheet.model.ExcelSheetContent;
import com.bistu.openlab.uofspreadsheet.namespace.NamespaceDeal;
import com.bistu.openlab.uofspreadsheet.util.XmlDomHelper;

/*
 *@author xiaoguang.gao@oracle.com
 *@version 2013-5-8 
 */
public class ExcelContentParse implements IXmlParse<ExcelContent>{
	private static ExcelContentParse parse = new ExcelContentParse();
	public static ExcelContentParse getInstance(){
		return parse;
	}
	private ExcelContentParse(){}

	@Override
	public ExcelContent readFromElement(Element root) {
		ExcelContent content = null;
		if(root!=null){
			List<Element> sheetEleList = root.selectNodes("表:工作表_E825");
			if(sheetEleList!=null&&sheetEleList.size()>0){
				content = new ExcelContent();//initial
				content.setSheetList(null);
				ExcelSheetParse sheetParse = ExcelSheetParse.getInstance();
				for(Element sheetEle : sheetEleList){
					content.addSheet(sheetParse.readFromElement(sheetEle));
				}				
			}
		}
		return content;
	}
	@Override
	public Element writeToElement(ExcelContent obj) {
		Element root = null;
		Document doc = null;
		URL url = ClassLoader.getSystemClassLoader().getResource("com/bistu/openlab/uofspreadsheet/resource/template/content.xml");
		try {
			URLConnection connection = url.openConnection();
			InputStream stream = connection.getInputStream();
			doc = XmlDomHelper.GetDocFromInputStream(stream);
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		root = (Element)doc.getRootElement().clone();
		if(obj!=null){		
			//clear its all of child nodes
			root.clearContent();
			List<ExcelSheet> sheetList = obj.getSheetList();
			if(sheetList!=null&&sheetList.size()>0){
				ExcelSheetParse sheetParse = ExcelSheetParse.getInstance();
				for(ExcelSheet sheet : sheetList){
					Element sheetEle = sheetParse.writeToElement(sheet);
					if(sheetEle!=null)root.add(sheetEle);
				}
			}
		}
		NamespaceDeal.AddNamespace(root);
		return root;
	}
}
